import { mapState, mapGetters } from 'vuex'
import { PAGINATION_TYPE } from '@/common/const'
import { CAROUSEL_ITEM_TYPES_MAP, CAROUSEL_TYPES_MAP } from '@/common/const-items'
import { EventBus } from '@/store/index'
import { COMPONENT_TYPES } from '@/common/const-wb'
import { isJSON } from '@/plugins/utils'
import { getPxOVwByValue } from '@/store/utils'
import { isHasOwnProperty } from '@/plugins/utils'

export const carousel = {
  created(){
    const data_ = {
      CAROUSEL_ITEM_TYPES_MAP: CAROUSEL_ITEM_TYPES_MAP,
      PAGINATION_TYPE: PAGINATION_TYPE,
      isPropagation: false,
      swiper_: null,
      swiperIndex: -1,
    };
    for(let key in data_) {
      this[key] = data_[key];
    }
    // import('swiper' /* webpackChunkName: "swiper" */).then((module) => {
    //   let Swiper = module.default
    //   this.initSwiper(Swiper)
    // })
    if(!window.Swiper && !this.commonAttr.isOtherBtnTrigger){
      this.dynamicsLoadScript(this.env.baseUrl + 'js/swiper-bundle.min.js?v=7', 'Swiper', this.initSwiper)
    }
    if(!this.isH5Edit){
      EventBus.$on("swiperChangePage", this.slideNext);
      EventBus.$on("swiperPre", this.slidePre);
      EventBus.$on("swiperNext", this.slideNext);
    }
  },
  computed: {
    ...mapGetters({
      currentPage: "getCurrentPage",
    }),
    ...mapState({
    }),
    swiperOption() {
      let this_ =  this
      let slideNum = 1
      if(this.commonAttr.carouselType ==  CAROUSEL_TYPES_MAP.slidesPerView && this.commonAttr.slideNum){
        slideNum = this.commonAttr.slideNum
      }
      let isNoSwipin_ = this.isNoSwiping
      return {
        updateOnWindowResize: true,
        preloadImages: this.preloadImages,//默认为true，Swiper会强制加载所有图片。
        runCallbacksOnInit: true,//slideChangeTransitionStart
        watchOverflow: true,//当没有足够的slide切换时，例如只有1个slide，swiper会失效且隐藏导航等。默认不开启这个功能。
        preventInteractionOnTransition: true,
        observer: true,
        noSwiping: isNoSwipin_,
        loop: this.isLoop,//影响点击事件，不能加这个
        lazy: {
          loadPrevNext: true,
        },
        autoplay: !this.isH5Edit && this.commonAttr.autoTurnPage ? {
          delay: this.commonAttr.turnPageTime*1000,
          disableOnInteraction: true,
        } : false,
        slidesPerView: slideNum,
        spaceBetween: this.commonAttr.slideSpace ? this.commonAttr.slideSpace : 20,
        freeMode: this.commonAttr.isFreeMode ? true : false,
        centeredSlides: true,
        initialSlide: this.commonAttr.initialSlide ? this.commonAttr.initialSlide : 0,//默认第三页
        on: {
          slideChangeTransitionEnd: function(e) {
            if(this_.isH5Edit){
              return
            }
            let itemIndex = this.activeIndex
            this_.onEmitSlideChange(e, itemIndex)
          },
        },
      }
    },
    swiper(){
      return this.swiper_
    },
    preloadImages(){
      if(this.item.cid == COMPONENT_TYPES.wb_imgs){
        return true
      }else{
        return false
      }
    },
    isLoop(){
      if(!this.isH5Edit && this.isHaveFrontSwiperEvent){
        return true
      }else{
        return isHasOwnProperty(this.commonAttr, "isLoop") ? this.commonAttr.isLoop : !this.isNoSwiping
      }
    },
    isNoSwiping(){
      let isNoSwiping_
      if(!this.isH5Edit && this.isHaveFrontSwiperEvent || this.commonAttr.itemType == CAROUSEL_ITEM_TYPES_MAP.question || this.commonAttr.itemType == CAROUSEL_ITEM_TYPES_MAP.different || this.item.cid == COMPONENT_TYPES.wb_videos){
        isNoSwiping_ = true
      }else{
        isNoSwiping_ = false
      }
      return isNoSwiping_
    },
    isHaveFrontSwiperEvent(){
      let isFrontSwiperEvent = this.searchFrontSwiperEvent(this.currentPage.components);
      return isFrontSwiperEvent;
    },
    getPaginationClass(){
      let classObj = {}
      classObj[this.commonAttr.paginationColorType] = true
      return classObj
    },
    getSwiperPreStyle(){
      if(this.commonAttr.preBtnUrl && this.commonAttr.preBtnUrl.length > 0){
        if(isHasOwnProperty(this.commonAttr, "swiperBtnWidth") && this.commonAttr.swiperBtnWidth){
          return {
            backgroundImage: "url(" + this.commonAttr.preBtnUrl + ")",
            width: getPxOVwByValue(this.commonAttr.swiperBtnWidth),
            height: getPxOVwByValue(this.commonAttr.swiperBtnHeight),
          }
        }else{
          return {
            backgroundImage: "url(" + this.commonAttr.preBtnUrl + ")",
          }
        }
      }
    },
    getSwiperNextStyle(){
      if(this.commonAttr.nextBtnUrl && this.commonAttr.nextBtnUrl.length > 0){
        if(isHasOwnProperty(this.commonAttr, "swiperBtnWidth") && this.commonAttr.swiperBtnWidth){
          return {
            backgroundImage: "url(" + this.commonAttr.nextBtnUrl + ")",
            width: getPxOVwByValue(this.commonAttr.swiperBtnWidth),
            height: getPxOVwByValue(this.commonAttr.swiperBtnHeight),
          }
        }else{
          return {
            backgroundImage: "url(" + this.commonAttr.nextBtnUrl + ")",
          }
        }
      }
    },
  },
  mounted(){
    if(this.commonAttr.isOtherBtnTrigger){
      this.slideNext();
    }else{
      this.initSwiper(window.Swiper);
    }
  },
  methods: {
    searchFrontSwiperEvent(components){
      let isFrontSwiperEvent = false;
      for(let i = 0, len = components.length; i < len; i++){
        let compData =  components[i];
        if(compData.events.frontEvents){
          isFrontSwiperEvent = true;
          return isFrontSwiperEvent;
        }
        if(compData.components && compData.components.length > 0){
          isFrontSwiperEvent = this.searchFrontSwiperEvent(compData.components);
        }
      }
      return isFrontSwiperEvent;
    },
    slideNext(){
      if(this.commonAttr.isOtherBtnTrigger){
        const pageId_ = 'page-' + this.pageId;
        const currentPageDom = document.getElementById(pageId_);
        if(currentPageDom){
          const lis = currentPageDom.getElementsByClassName("swiper-li");
          this.swiperIndex++;
          if(this.swiperIndex >= this.lists.length){
            this.swiperIndex = this.lists.length - 1;
          }
          this.swiperIndex = this.swiperIndex%this.lists.length;
          this.$store.commit("updateInteractionData", { swiperIndex: this.swiperIndex });
          _.forEach(lis, (li, index) => {
            if(index == this.swiperIndex){
              li.style.display = "block";
              this.addClass(li, "animate__fadeIn");
              this.addClass(li, "animate__animated");
            }else{
              li.style.display = "none";
              this.removeClass(li, "animate__fadeIn");
              this.removeClass(li, "animate__animated");
            }
          })
        }
      }else{
        if(this.swiper){
          let len =  this.carouselList ? this.carouselList.length : this.lists.length;
          this.$store.commit("updateInteractionData", { swiperIndex: this.swiper.activeIndex%len });
          if(this.swiper.activeIndex < len) {
            this.swiper.slideNext();
            //处理 事件 clickCompIdMap
          }
        }
      }
    },
    slidePre(){
      if(this.commonAttr.isOtherBtnTrigger){
        const pageId_ = 'page-' + this.pageId;
        const currentPageDom = document.getElementById(pageId_);
        if(currentPageDom){
          const lis = currentPageDom.getElementsByClassName("swiper-li");
          this.swiperIndex--;
          if(this.swiperIndex < 0){
            this.swiperIndex = 0;
          }
          this.swiperIndex = this.swiperIndex%this.lists.length;
          this.$store.commit("updateInteractionData", { swiperIndex: this.swiperIndex });
          _.forEach(lis, (li, index) => {
            if(index == this.swiperIndex){
              li.style.display = "block";
              this.addClass(li, "animate__fadeIn");
              this.addClass(li, "animate__animated");
            }else{
              li.style.display = "none";
              this.removeClass(li, "animate__fadeIn");
              this.removeClass(li, "animate__animated");
            }
          })
        }
      }else{
        if(this.swiper){
          this.$store.commit("updateInteractionData", { swiperIndex: this.swiper.activeIndex%this.lists.length });
          this.swiper.slideNext();
        }
      }
    },
    initSwiper(Swiper){
      let swiperDom = this.$refs.swiper
      if(!Swiper || !swiperDom){
        return
      }
      if(this.swiper_){
        this.swiper_.destroy();
      }
      let swiperContainer = swiperDom.getElementsByClassName("swiper-container-h")[0];
      if(!swiperContainer){
        swiperContainer = this.$refs.scrollSwiper;
      }
      let swiperOption = this.swiperOption;
      if(this.commonAttr.paginationType == PAGINATION_TYPE[2].value || this.commonAttr.paginationType == PAGINATION_TYPE[3].value){
        let prevEl = document.getElementById(this.item.id + '-prev')
        let nextEl = document.getElementById(this.item.id + '-next')
        swiperOption.navigation = {
          prevEl: prevEl,
          nextEl: nextEl,
        };
      }
      if(this.commonAttr.effect) {
        swiperOption.effect = this.commonAttr.effect;
        if(this.commonAttr.paginationType > PAGINATION_TYPE[0].value){
          let elPagination = document.getElementById(this.item.id + '-pagination')
          swiperOption.pagination = {
            el: elPagination,
            clickable: true,
          };
        }

        if(this.commonAttr.effect == "coverflow"){
          swiperOption.slidesPerView = 3;
          let coverflowEffect = {
            rotate: 30,
            stretch: 0,
            depth: 80,
            modifier: 1,
            slideShadows : true,
          };
          if(this.commonAttr.effectParams && isJSON(this.commonAttr.effectParams)){
            _.merge(coverflowEffect, JSON.parse(this.commonAttr.effectParams))
          }
          swiperOption.coverflowEffect = coverflowEffect;
        }
      }

      this.swiper_ = new Swiper(swiperContainer, swiperOption);
      this.carouselDot();
    },
    slideTo({slideIndex}) {
      if(this.swiper){
        this.swiper.slideTo(slideIndex, 500, false)
      }
    },
    //图片组和视频组会调用这个方法，在轮播组中会被覆盖
    onEmitSlideChange(e, itemIndex){
      this.commonAttr.itemIndex = itemIndex

      if(e && !this.commonAttr.autoTurnPage){
        let jumpUrl = this.jumpUrl_ + itemIndex
        let comType = "click"
        let wModule = "jump"
        this.onPostStatics(e, { comType, wModule,  jumpUrl })
      }
    },
    carouselDot(){
      let widHei = '10px'
      if(this.isH5Edit){
        widHei = '20px'
      }
      let bullets =  this.$refs.swiper.getElementsByClassName("swiper-pagination-bullet")
      _.forEach(bullets, (bullet) => {
        bullet.style.width = widHei
        bullet.style.height = widHei
      })
    },
    resetSwiper(){
      if(this.swiper_){
        this.swiper_.init();
        this.swiper_.activeIndex = 0;
        this.swiper_.slideTo(0, 0);
      }
      this.clickQuestionType = {};
    }
  },
  beforeUnmount(){
    this.resetSwiper();
    if(this.swiper_) {
      this.swiper_.destroy();
    }
    this.ruleValues = {};
  }
}
